//
//  HMOAuthViewController.swift
//  HMWeibo
//
//  Created by wulei on 15/12/8.
//  Copyright © 2015年 wulei. All rights reserved.
//

import UIKit
import SVProgressHUD
class HMOAuthViewController: UIViewController {

    private lazy var webview = UIWebView()
    
    // 监听方法
  @objc private func close() {
    
    SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
/// 自动填充用户名和密码
    @objc private func autoFill() {
        
        let JS = "document.getElementById('userId').value = '13716617484';" + "document.getElementById('passwd').value = 'wulei43416646';"
        webview.stringByEvaluatingJavaScriptFromString(JS)
    }
    
    // 设置界面
    override func loadView() {
        // 在开发中,如果是用纯代码开发,视图最好都指定背景颜色,如果为nil,会影响渲染效率
        
        view = webview
        
        // 设置代理
        webview.delegate = self
        
        // 设置导航栏
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style:.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style:.Plain, target: self, action: "autoFill")
        
    }
    
    
    //
    override func viewDidLoad() {
        super.viewDidLoad()
//        view.backgroundColor = UIColor.whiteColor()

        
        webview.loadRequest(NSURLRequest(URL: HMNetworkTools.sharedTools.oauthURL))
        
        
        
    }



}




//MARK: - UIWeiboViewDelegate
extension HMOAuthViewController: UIWebViewDelegate {
    /// 将要加载请求的代理方法
    /// - parameter webView:        webView
    /// - parameter request:        将要加载的请求,
    /// - parameter navigationType: 页面跳转的方式
    /// - returns:  返回false 不加载 返回true 加载
    
    
    //    case LinkClicked    点击某个链接去跳转
    //    case FormSubmitted  点击表单提交按钮跳转
    //    case BackForward    点击前进后退的
    //    case Reload         重新加载页面
    //    case FormResubmitted 弹出窗口 重复提交,重复购买
    //    case Other
    
   
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 目标: 如果是百度就不加载
        // 判断访问的主机,是不是 www.baidu.com
        guard let url = request.URL where url.host == "www.baidu.com" else {
            return true
        }
        
        // 判断 从百度地址中提取的 code = 是否存在
        guard let query = url.query where query.hasPrefix("code=") else {
            print("取消授权")
            close()
            return false
        }
        
        
        // 主机地址
//        print(url.host)
        
        // 查询字符串
//        print(url.query)
        
        let code = query.substringFromIndex("code=".endIndex)
//        print(query)
//        print("授权码是:" + code)
        
        HMUserAccountViewModel.sharedUserAccountViewModel.loadAcessToken(code) { (isSuccess) -> () in
            if !isSuccess {
                SVProgressHUD.showInfoWithStatus("您的网速不给力")
                
                delay(1){
                    self.close()
                }
                return
                
            }
            
            // dismissViewController 一定要等它消毁之后再去发通知,否则的话之前的控制器不会被释放
            self.dismissViewControllerAnimated(false){
                SVProgressHUD.dismiss()
                
                // 通知中心是同步的,一旦发送通知,会先执行监听方法,直到结束后,才会执行后续的代码
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: "welcome")
            }
        }
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
